import { MicroAppStateActions } from 'qiankun'

// qiankun Actions通信
let actions: MicroAppStateActions

interface globalStateItf {
  userInfo: {
    id: string
    account: string
    avatar?: string
    nickname: string
  }
  currentChatRecord?: {}[]
}
// 乾坤全局状态
let globalState: globalStateItf

// 初始化一个 actions实例
const initActions = (a: MicroAppStateActions) => {
  actions = a

  // 修改状态或者说是进行初始化状态
  actions.setGlobalState({})

  watchGlobalStateChange()
}

// 监听状态
const watchGlobalStateChange = () => {
  // 注册观察者函数
  // state: 变更后的状态; prev 变更前的状态
  // onGlobalStateChange 第二个参数为 true，表示立即执行一次观察者函数
  // @ts-ignore
  actions.onGlobalStateChange((state, prev) => {
    // console.log('Main application ', state, prev)
    globalState = { ...globalState, ...state }
    console.log('Main application globalState :', globalState)
  }, true)
}

// 获取全局状态
const getGlobalState = (): globalStateItf => globalState

export { initActions, actions as qiankunActions, getGlobalState }
